package org.jash.shop2111.mvvm

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import org.jash.shop2111.utils.Event
import org.jash.shop2111.utils.bus
import java.lang.reflect.ParameterizedType

@Suppress("UNCHECKED_CAST")
abstract class BaseFragment<B:ViewDataBinding, VM: BaseViewModel>: Fragment() {
    init {
        val methods = javaClass.declaredMethods // 所有声明的方法
//        javaClass.methods 所有可见的方法
        for (m in methods) {
            val event = m.getAnnotation(Event::class.java)
            event?.let { e ->
                bus.observe(this) {
                    if (it.first == e.value)
                        m.invoke(this, it.second)
                }
            }
        }
    }
    private val types by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    val binding:B by lazy {
        val clazz  = types[0] as Class<B>
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        method.invoke(null, layoutInflater) as B
    }

    val viewModel: VM by lazy {
        val clazz = types[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.errorLiveData.observe(this, ::error)
        initData()
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = binding.root

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initView()
    }

    abstract fun initData()

    abstract fun initView()

    open fun error(throwable: Throwable) {
        Toast.makeText(requireContext(), throwable.message, Toast.LENGTH_SHORT).show()
        throwable.printStackTrace()
    }

}